/**
 * 异常时间交易分析器 - 对象中心化版本
 * 检测深夜或节假日等异常时段的大额交易
 */

class OffHourTradingAnalyzer extends BaseAnalyzer {
  constructor(caseId, targetSubject = null) {
    super(caseId, targetSubject);
    this.name = '异常时间交易';
    this.description = '检测深夜或非工作时段的大额交易';
  }

  async analyze(params = {}) {
    const offHourStart = params.offHourStart || 22;
    const offHourEnd = params.offHourEnd || 6;
    const minAmount = params.minAmount || 50000;

    const accountFilter = this.getBankAccountFilter();

    const sql = `
            SELECT 
                account_card,
                customer_name,
                transaction_time,
                transaction_amount,
                debit_credit_flag,
                counterparty_name,
                CAST(strftime('%H', transaction_time) AS INTEGER) as hour
            FROM bank_transactions
            WHERE case_id = ?
                AND ABS(transaction_amount) >= ?
                AND (CAST(strftime('%H', transaction_time) AS INTEGER) >= ?
                     OR CAST(strftime('%H', transaction_time) AS INTEGER) < ?)
                ${accountFilter}
            ORDER BY ABS(transaction_amount) DESC
            LIMIT 100
        `;

    const result = await this.runQuery(sql, [
      this.caseId,
      minAmount,
      offHourStart,
      offHourEnd
    ]);

    if (!result.success) {
      return this.createResult('off_hour', this.name, [], '查询失败: ' + result.message, 'danger');
    }

    const data = result.data;
    const totalAmount = data.reduce((sum, r) => sum + Math.abs(r.transaction_amount), 0);
    const summary = data.length > 0
      ? `检测到 ${data.length} 笔异常时间交易，累计金额 ¥${this.formatAmount(totalAmount)}`
      : '未检测到异常时间交易';

    const level = data.length > 10 ? 'warning' : (data.length > 0 ? 'info' : 'info');

    return this.createResult('off_hour', this.name, data, summary, level);
  }

  renderResult(data) {
    if (!data || data.length === 0) {
      return '<div class="empty-result" style="padding:40px; text-align:center; color:#999;">✓ 未发现异常时间交易</div>';
    }

    let html = `
      <table class="analysis-result-table" style="width:100%; border-collapse:collapse; font-size:0.9rem;">
        <thead style="background:#f5f7fa;">
          <tr>
            <th style="padding:10px; border:1px solid #e0e0e0;">账号/户名</th>
            <th style="padding:10px; border:1px solid #e0e0e0;">交易时间</th>
            <th style="padding:10px; border:1px solid #e0e0e0; text-align:right;">交易金额</th>
            <th style="padding:10px; border:1px solid #e0e0e0;">对方</th>
          </tr>
        </thead>
        <tbody>
    `;

    data.forEach((row, index) => {
      const rowStyle = index % 2 === 0 ? 'background:#fafafa;' : '';
      const amountColor = row.debit_credit_flag === '借' ? '#67c23a' : '#f56c6c';
      html += `<tr style="${rowStyle}">`;
      html += `<td style="padding:8px; border:1px solid #e0e0e0;">${row.customer_name}<br><small style="color:#909399;">${row.account_card}</small></td>`;
      html += `<td style="padding:8px; border:1px solid #e0e0e0;">${this.formatDate(row.transaction_time)} <span style="color:#e6a23c; font-weight:bold;">(${row.hour}时)</span></td>`;
      html += `<td style="padding:8px; border:1px solid #e0e0e0; text-align:right; color:${amountColor}; font-weight:bold;">¥${this.formatAmount(row.transaction_amount)}</td>`;
      html += `<td style="padding:8px; border:1px solid #e0e0e0;">${row.counterparty_name || '-'}</td>`;
      html += '</tr>';
    });

    html += '</tbody></table>';
    return html;
  }
}

window.OffHourTradingAnalyzer = OffHourTradingAnalyzer;
